package com.uatair.common.mqtt.util;

import com.uatair.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class UAesUtil {

    private static final String UA_KEY = "ua_aes_2012_key_d_2133889";
    private static final int BLOCK_LENGTH = 16;

    // Java 8兼容的文件下载方法
    private static byte[] downloadFile(String fileUrl) throws Exception {
        URL url = new URL(fileUrl);
        try (InputStream in = url.openStream();
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            return out.toByteArray();
        }
    }

    // 调整数据长度为16的整数倍
    private static byte[] adjustLength(byte[] input) {
        int newLength = input.length + (BLOCK_LENGTH - (input.length % BLOCK_LENGTH)) % BLOCK_LENGTH;
        return Arrays.copyOf(input, newLength);
    }

    // 解密方法
    public static byte[] uaDecrypt(byte[] in) {
        if (in == null || in.length == 0) return null;

        // 准备密钥（确保16字节长度）
        byte[] keyBytes = Arrays.copyOf(UA_KEY.getBytes(StandardCharsets.UTF_8), 16);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");

        // 使用AES/ECB/PKCS5Padding模式
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            return cipher.doFinal(in);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException |
                 BadPaddingException e) {
            throw new RuntimeException(e);
        }
    }

    public static List<String> downloadAndParseFile(String fileUrl) {
        log.info("文件url:{}", fileUrl);
        // 创建URL对象
        URL url = null;
        try {
            url = new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }

        // 打开输入流
        try (InputStream inputStream = url.openStream();
             InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
             BufferedReader reader = new BufferedReader(inputStreamReader)) {

            String line;
            int lineNumber = 0;
            // 逐行读取并处理
            List<String> lines = new ArrayList<>();
            while ((line = reader.readLine()) != null) {
                lineNumber++;
//                System.out.println("行 " + lineNumber + ": " + line);
                lines.add(line);
            }
            return lines;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    public static double calculateSpeedFromComponents(double vx, double vy, double vz) {
        return Math.sqrt(vx * vx + vy * vy + vz * vz);
    }

    public static void main(String[] args) {
        String fileUrl = "https://ag.uatair.com/agro_minio/agricultural-common/uavData/612237163124/2025-04-30/557&612237163124_1745997020391.txt";
        try {
//            String original = new String(Files.readAllBytes(Paths.get("C:\\Users\\92517\\Downloads\\612737193106_1748949330798&612737193106_1748949328148.txt")),StandardCharsets.UTF_8);
//            byte[] decodedData = Base64.decodeBase64(original);
//            byte[] decrypted = uaDecrypt(decodedData);
//            String jsonData = new String(decrypted, StandardCharsets.UTF_8);
//            System.out.println(jsonData);
            List<String> strings = downloadAndParseFile(fileUrl);
            if (!strings.isEmpty()) {
                for (String string : strings) {
                    if (StringUtils.isNotEmpty(string)) {
                        byte[] decodedData1 = Base64.decodeBase64(string);
                        byte[] decrypted1 = uaDecrypt(decodedData1);
                        String jsonData1 = new String(decrypted1, StandardCharsets.UTF_8);
                        System.out.println(jsonData1);
                    }
                }
            }
            /*byte[] encryptedData = downloadFile(fileUrl);
            byte[] decodedData1 = Base64.decodeBase64(encryptedData);
            byte[] decrypted1 = uaDecrypt(decodedData1);
            String jsonData1 = new String(decrypted1, StandardCharsets.UTF_8);
            System.out.println(jsonData1);*/

        } catch (Exception e) {
            System.err.println("解密过程中发生错误:");
            e.printStackTrace();
        }
    }
}
